export default class UpdateNotifier {
  constructor(options = {}) {
    // 默认配置
    this.options = {
      checkInterval: options.checkInterval || 30 * 1000, // 检查间隔
      autoRefresh: options.autoRefresh !== false, // 是否自动刷新
      refreshDelay: options.refreshDelay || 10 * 1000, // 自动刷新延迟
      hiddenStop: options.hiddenStop !== false, // 页面隐藏时停止检查
      versionFile: options.versionFile || "/version.json", // 版本文件路径
      ...options,
    };

    // 状态变量
    this.currentVersion = null;
    this.newVersion = null;
    this.timer = null;
    this.countdownTimer = null;
    this.isChecking = false;
    this.isPageHidden = false;

    // 事件监听器
    this.listeners = {
      update: [],
      beforeRefresh: [],
    };

    // 初始化
    this.init();
  }

  // 初始化
  init() {
    this.getCurrentVersion().then((version) => {
      this.currentVersion = version;
      this.start();
    });

    // 页面可见性变化监听
    if (this.options.hiddenStop) {
      document.addEventListener(
        "visibilitychange",
        this.handleVisibilityChange
      );
    }
  }

  // 获取当前版本
  async getCurrentVersion() {
    try {
      const response = await fetch(
        this.options.versionFile + "?t=" + Date.now()
      );
      const data = await response.json();
      return data.version;
    } catch (e) {
      console.error("[Version Notifier] Failed to get current version:", e);
      return Date.now().toString(); // 返回时间戳作为版本号
    }
  }

  // 开始检查更新
  start() {
    if (this.timer) clearTimeout(this.timer);

    this.timer = setTimeout(() => {
      this.checkUpdate();
      this.start();
    }, this.options.checkInterval);

    this.checkUpdate();
  }

  // 停止检查
  stop() {
    if (this.timer) clearTimeout(this.timer);
    this.timer = null;
  }

  // 检查更新
  async checkUpdate() {
    if (this.isChecking || this.isPageHidden) return;
    this.isChecking = true;

    try {
      const newVersion = await this.getCurrentVersion();

      if (this.currentVersion !== newVersion) {
        this.newVersion = newVersion;
        this.emit("update", newVersion);

        // 自动刷新
        if (this.options.autoRefresh) {
          this.scheduleRefresh();
        }
      }
    } catch (e) {
      console.error("[Version Notifier] Update check failed:", e);
    } finally {
      this.isChecking = false;
    }
  }

  // 安排刷新
  scheduleRefresh() {
    if (this.countdownTimer) clearInterval(this.countdownTimer);

    const delay = this.options.refreshDelay;
    let secondsLeft = Math.floor(delay / 1000);

    // 倒计时
    this.countdownTimer = setInterval(() => {
      secondsLeft -= 1;

      if (secondsLeft <= 0) {
        this.refreshPage();
      } else {
        this.emit("beforeRefresh", secondsLeft);
      }
    }, 1000);
  }

  // 刷新页面
  refreshPage() {
    this.emit("beforeRefresh", 0);
    location.reload();
  }

  // 处理页面可见性变化
  handleVisibilityChange = () => {
    this.isPageHidden = document.hidden;

    if (this.isPageHidden) {
      this.stop();
    } else {
      this.start();
    }
  };

  // 事件监听
  on(event, callback) {
    if (this.listeners[event]) {
      this.listeners[event].push(callback);
    }
  }

  // 事件触发
  emit(event, ...args) {
    if (this.listeners[event]) {
      this.listeners[event].forEach((cb) => cb(...args));
    }
  }

  // 销毁
  destroy() {
    this.stop();
    document.removeEventListener(
      "visibilitychange",
      this.handleVisibilityChange
    );
  }
}
